<template>
  <div class="config-box">
    <div class="map">
      <Map @onload="handleMapLoad" :options="mapOptions" />
    </div>
    <div class="page-back-box" @click="goBack"><span class="back-icon"></span> 返回</div>
    <div class="select-box">
      <SchemeSelect
        :placeholder="state.placeholderOne"
        :define-options="state.optionsOne"
        :images="'u97.png'"
        @changeSelect="changeSelect"
      />
      <SchemeList
        class="marg-top"
        @clickLi="clickLi"
        @handleAdd="handleAdd"
        :images="'u101.png'"
        :title="'预报断面'"
        :data-list="state.sectionArr"
        :btn-name="'导入预报断面'"
        :showbtn="false"
      />
    </div>
    <div class="select-basin">
      <WaterLayer />
    </div>
    <!-- <div class="bottom-btn">
      <span class="btn-topology" :class="{ active: btnBg }" @click="showDiglog(0)">预报对象拓扑关系</span>
      <span class="btn-topology" :class="{ active: !btnBg }" @click="showDiglog(1)">主河道断面拓扑关系</span>
    </div>-->
    <!-- 预报对象拓扑关系弹窗 -->
    <ForecastObj
      :sectionObj="sectionObj"
      :rightBox="rightBox"
      @clickDiglog="clickDiglog"
      @localtionBtns="localtionBtns"
    />
    <RiverSection :sectionObj="sectionObj" :rightBox="rightBox" @clickDiglog="clickDiglog" />

    <!-- 弹窗 -->
    <importFile :dialogVisible="showDialog" @closeDialog="closeDig" />
  </div>
</template>
<script setup>
import importFile from './cpns/importFile.vue'
import { reactive, markRaw, ref, onMounted } from 'vue'
import Map from '@/components/app-map/map.vue'
import SchemeSelect from '@/components/app-publicui/scheme-select.vue'
import WaterLayer from './cpns/WaterLayer.vue'
import ForecastObj from './cpns/ForecastObj.vue'
import RiverSection from './cpns/RiverSection.vue'
import SchemeList from '@/components/app-publicui/scheme-list.vue'
import sec_info from '@/assets/data/com_data/sec_info'
import { getZone, getSectionTree } from '@/services/modules/model-config'

import emitter from '@/utils/bus'
// 添加地图操作方法
import {
  removeLayer,
  addTileLayer,
  addDynamicLayer,
  addDynamicLayerShowAll,
  locatePoint,
  addSecPoints,
  addSecName,
  addTopology,
  removeBasinVectorTiles,
  addGeojsontoFly
} from '@/utils/mapUtils'
//地图api
import {
  getPPtnGeomList,
  getSecGeomList,
  getNodeGeomList,
  getTopologyGeomList,
  getSectionUnitGeom
} from '@/services/modules/map.js'
//导入图层
import {
  WATA_BOUND_LAYER,
  SEC_LAYER,
  SEC_NAME_LAYER,
  TOPOLOGY_LAYER,
  UNIT_SEC_LAYER,
  UNIT_COMPUT_LAYER,
  UNIT_PART_LAYER,
  WATA_LAYER
} from '@/constants'

let showDialog = ref(false)
const zoneId = ref(1)
// 地图初始化参数
const mapOptions = { crs: 'EPSG:4490', basemaps: [] }

const state = reactive({
  placeholderOne: '大汶河流域',
  optionsOne: [
    {
      value: '1',
      label: '大汶河流域'
    }
  ],
  // 拓扑关系
  tpflag: '',
  sectionArr: [],
  secGeoData: {},
  topologyGeoData: {}
})

const sectionObj = reactive({
  title: '',
  id: '',
  zoneId: ''
})
const secStyle = reactive({
  fill: true,
  fillColor: '#3388ff',
  // fillColor: 'white',
  fillOpacity: 0.3,
  outline: true,
  outlineWidth: 1,
  outlineColor: '#0000FF',
  outlineOpacity: 0.5
})
// 点击左侧列表将数据传给弹框
const rightBox = ref(false)
const btnBg = ref(true)

const clickLi = (item) => {
  sectionObj.title = item.title
  sectionObj.id = item.id
  sectionObj.blkcd = item.blkcd
  sectionObj.zoneId = zoneId
  removeBasinVectorTiles(mapInstance, UNIT_SEC_LAYER)
  removeBasinVectorTiles(mapInstance, UNIT_COMPUT_LAYER)
  removeBasinVectorTiles(mapInstance, UNIT_PART_LAYER)
  removeBasinVectorTiles(mapInstance, WATA_LAYER)
  //查询计算单元坐标信息
  getSectionUnitGeom({ blkcd: item.blkcd }).then((res) => {
    if (res.code === 200) {
      if (res.data) {
        addGeojsontoFly(mapInstance, res.data, UNIT_SEC_LAYER, secStyle)
        // let arr = multipolygonToLnglats(res.data.geom)
        // addTopologyPosition(mapInstance, arr, UNIT_SEC_LAYER, secStyle)
      }
    }
  })
  //当预报对象拓扑关系选中
  if (btnBg.value === true) {
    rightBox.value = true
  } else {
    rightBox.value = false
  }
  // console.log(btnBg.value)
}
const clickDiglog = (item) => {
  rightBox.value = item
}
const localtionBtns = (id) => {
  // updateJsUnitSecGraphic(mapInstance, id, WATA_LAYER)
}
//切换zone（大汶河）
const changeSelect = async (v) => {
  if (v == 1) {
    locatePoint(mapInstance, 117.1775, 36.06469, 10)
  } else if (v == 2) {
    locatePoint(mapInstance, 118.379657, 35.018398, 10)
  }

  zoneId.value = v
  getLeftTree()
  // 切换流域
  // handleMapLoad({ mapInstance })
  await SecGeomList()
  await TopologyGeomList()
  // 预报对象
  addSecPoints(mapInstance, state.secGeoData.features, SEC_LAYER)
  // 添加断面名称
  addSecName(mapInstance, state.secGeoData.features, SEC_NAME_LAYER)
  // 拓扑结构
  addTopology(mapInstance, state.topologyGeoData, TOPOLOGY_LAYER)
}
//导入预报断面
const handleAdd = () => {
  showDialog.value = true
}
const closeDig = (v) => {
  showDialog.value = v
}
const reductionDiglog = (item) => {
  console.log(item)
  openDiglog.value = item
}
// 控制按钮背景颜色

// 打开右侧弹框
//默认打开预报
const showDiglog = (value) => {
  if (value === 0) {
    // 打开预报对象拓扑关系
    btnBg.value = true
    emitter.emit('openRightDiglog', value)
  } else {
    btnBg.value = false
    emitter.emit('openRightDiglog', value)
  }
}
emitter.on('goConfig', (obj) => {
  if (obj.flag === 1) {
    state.tpflag = markRaw(ForecastObj)
    return
  } else if (obj.flag === 2) {
    state.tpflag = markRaw(RiverSection)
    return
  }
  state.modelShow = obj.showCf
})
const goBack = () => {
  emitter.emit('goback', true)
}
//地图获取预报对象
function SecGeomList() {
  return new Promise((resolve, reject) => {
    getSecGeomList({ zoneId: zoneId.value }).then((res) => {
      if (res.code === 200) {
        console.log(res.data, 889)
        state.secGeoData = res.data
        resolve(state.secGeoData)
      }
    })
  })
}
//地图获取拓扑线
function TopologyGeomList() {
  return new Promise((resolve, reject) => {
    getTopologyGeomList({ zoneId: zoneId.value }).then((res) => {
      if (res.code === 200) {
        state.topologyGeoData = res.data
        resolve(state.topologyGeoData)
      }
    })
  })
}
let mapInstance = null
/**
 * 地图实例完成后的调用函数
 */
const handleMapLoad = ({ map }) => {
  setTimeout(async () => {
    mapInstance = map
    await SecGeomList()
    await TopologyGeomList()
    //测试
    const layerUrlS = mapUrl
    // const layerUrlS =
    //   'https://giskg-sdsl.gistack.cn/OneMapServer/rest/services/Shandong_SDDOM/MapServer'
    addTileLayer(mapInstance, layerUrlS, 0, 74, '山东底图')
    const layerUrl =
      'https://giskg-sdsl.gistack.cn/OneMapServer/rest/services/Shandong_dwh05mdom/MapServer'
    addTileLayer(mapInstance, layerUrl, 4, 71, '0.5米卫星影像')
    addDynamicLayerShowAll(
      mapInstance,
      'https://giskg-sdsl.gistack.cn/OneMapServer/rest/services/L1_Liuyujie/MapServer',
      12,
      11,
      '流域界'
    )
    addDynamicLayerShowAll(
      mapInstance,
      'https://giskg-sdsl.gistack.cn/OneMapServer/rest/services/L1_xiaoliuyu/MapServer',
      13,
      12,
      '小流域'
    )
    addDynamicLayerShowAll(
      mapInstance,
      'https://giskg-sdsl.gistack.cn/OneMapServer/rest/services/L1_heliu/MapServer',
      14,
      13,
      '河流'
    )
    addDynamicLayerShowAll(
      mapInstance,
      'https://giskg-sdsl.gistack.cn/OneMapServer/rest/services/Shandong_hupo/MapServer',
      15,
      14,
      '湖泊'
    )
    addDynamicLayerShowAll(
      mapInstance,
      'https://giskg-sdsl.gistack.cn/OneMapServer/rest/services/Shandong_shuikumian/MapServer',
      16,
      15,
      '水库面'
    )
    // 预报对象
    addSecPoints(mapInstance, state.secGeoData.features, SEC_LAYER)
    // 添加断面名称
    addSecName(mapInstance, state.secGeoData.features, SEC_NAME_LAYER)
    // 拓扑结构
    addTopology(mapInstance, state.topologyGeoData, TOPOLOGY_LAYER)
  }, 100)
}
emitter.on('layerOperation', (value) => {
  const layerInfo = value
  switch (layerInfo.lyType) {
    case 'dynamic':
      console.log(value)
      if (layerInfo.isShow) {
        addDynamicLayerShowAll(
          mapInstance,
          layerInfo.url,
          layerInfo.lyIndex,
          layerInfo.id,
          layerInfo.name
        )
      } else {
        removeLayer(mapInstance, layerInfo.id)
      }

      break
    case 'tile':
      if (layerInfo.isShow) {
        addTileLayer(mapInstance, layerInfo.url, layerInfo.lyIndex, layerInfo.id, layerInfo.name)
      } else {
        removeLayer(mapInstance, layerInfo.id)
      }
      break
    default:
      break
  }
})

const getLeftTree = () => {
  getSectionTree({
    zoneId: zoneId.value
  }).then((res) => {
    if (res.code === 200) {
      state.sectionArr = res.data.map((item) => ({
        title: item.blknm,
        id: item.id,
        blkcd: item.blkcd
      }))
      clickLi(state.sectionArr[0])
    }
  })
}
function initData() {
  return new Promise((resolve, reject) => {
    getZone().then((res) => {
      if (res.code === 200) {
        state.optionsOne = res.data
        zoneId.value = res.data[0].id
        getLeftTree()
      }
    })
  })
}

onMounted(() => {
  initData()
})
</script>
<style lang="less" scoped>
.config-box {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  .map {
    position: relative;
    width: 100%;
    height: 100%;
  }
  .select-box {
    display: flex;
    flex-direction: column;
    width: 200px;
    height: auto;
    position: absolute;
    top: 50px;
    left: 30px;
    .marg-top {
      margin-top: 20px;
    }
    .header-select {
      width: 200px;
      margin-right: 20px;
    }
  }
  .select-basin {
    position: absolute;
    bottom: 40px;
    left: 20px;
    width: 210px;
    height: auto;
  }
  /* .bottom-btn {
    position: absolute;
    display: flex;
    justify-content: space-between;
    height: 40px;
    bottom: 30px;
    left: 35%;
    .btn-topology {
      margin-right: 30px;
      padding: 3px 20px;
      height: 30px;
      border: 1px solid rgba(22, 155, 213, 1);
      color: rgb(35, 9, 237);
      background-color: #ffffff;
      line-height: 30px;
      border-radius: 5px;
      text-align: center;
      cursor: pointer;
      &.active {
        background-color: rgba(22, 155, 213, 1);
        color: white;
      }
    }
  } */
}
</style>
